package cn.tedu;
import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

public class LogServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(LogServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String info = URLDecoder.decode(request.getQueryString(), "utf-8");
        // 首先按&切分，获取属性对，然后获取属性值，用|拼接在一起
        // 处理后的形式: http://localhost:8080/FluxAppServer/b.jsp|b.jsp|页面B...
        String[] kvs = info.split("\\&");
        StringBuffer buffer = new StringBuffer();
        for (String kv : kvs) {
            // 获取value时，可能出现报错, 比如ref属性(来路页面)，可能没有value
            String value = kv.split("=").length == 2 ? kv.split("=")[1] : "";
            buffer.append(value + "|");
        }
        // 拼接用户访问的IP地址
        buffer.append(request.getRemoteAddr());
        // Logger记录的级别从低到高依次为: debug->info->warn->error->fatal
        // 此外，使用log4j还需要有log4j.properties
        logger.info(buffer);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
